/**
 * Copyright 2009 Marc Stogaitis and Mimi Sun
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gmote.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.image.codec.jpeg.ImageFormatException;

public class GmoteHttpServer {
  private static final Logger LOGGER = Logger.getLogger(GmoteHttpServer.class.getName());
  private static final int HTTP_NOT_FOUND = 404;

  private Socket connectionSocket;
  
  public GmoteHttpServer(Socket connectionSocket) {
    this.connectionSocket = connectionSocket;
  }
  
  public void handleHttpRequestAsync(List<String> latestSessionIds) {
    HttpConnectionHandler conHandler = new HttpConnectionHandler(latestSessionIds);
    new Thread(conHandler).start();
  } 
  private void handleHttpRequest(List<String> latestSessionIds) throws ImageFormatException, InterruptedException {
    
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
      List<String> header ;
      String requestedUrl = "";
      
      String[] urlSplit = requestedUrl.split("\\?");
      if (urlSplit.length < 2 || urlSplit[1].indexOf("=") < 0) {
        LOGGER.warning("Encountered a malformed url. It's missing a session param. Ignoring request: " + requestedUrl);
        return;
      }
      File file = new File(urlSplit[0]);
      
      if (!file.exists()) {
        throw new FileNotFoundException("The file was not found: " + file.getName());
      }   
      PrintWriter ps = new PrintWriter(connectionSocket.getOutputStream());       
    } catch (UnsupportedEncodingException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (IOException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } 
  }
  public class HttpConnectionHandler implements Runnable {

    private List<String> latestSessionIds;
    
    public HttpConnectionHandler(List<String> latestSessionIds) {
      this.latestSessionIds = latestSessionIds;
    }

    public void run() {
      try {
        handleHttpRequest(latestSessionIds);
        LOGGER.info("Done handlerequest(). Closing connection.");
      } catch (Exception ex) {
        // Catching all exceptions since this is the top layer of our app.
        LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
        
          try {
            PrintWriter ps = new PrintWriter(connectionSocket.getOutputStream());
            ps.println("HTTP/1.0 " + HTTP_NOT_FOUND + " not found " + ex.getMessage());
          } catch (IOException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
          }       
      } finally {
        LOGGER.info("Closing http connection");
        try {
          connectionSocket.close();
        } catch (IOException e) {
          LOGGER.log(Level.SEVERE, e.getMessage(), e);
        }
      }
    }
  }
  
}


 